﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace InForTheCloud.OAuthLite
{
    public class OAuthSecret
    {
        string consumerKey;
        string consumerSecret;
        string token;
        string tokenSecret;
        public OAuthSecret(string consumerKey, string consumerSecret, string token, string tokenSecret)
        {
            if (string.IsNullOrEmpty(consumerKey))
                throw new ArgumentNullException("consumerKey");
            if (string.IsNullOrEmpty(consumerSecret))
                throw new ArgumentNullException("consumerKey");
            if (!string.IsNullOrEmpty(token)
                && string.IsNullOrEmpty(tokenSecret))
                throw new ArgumentNullException("tokenSecret");

            this.consumerKey = consumerKey;
            this.consumerSecret = consumerSecret;
            this.token = token;
            this.tokenSecret = tokenSecret;
        }

        public OAuthSecret(string consumerKey, string consumerSecret)
            : this(consumerKey, consumerSecret, null, null)
        { 
        
        }

        public string ConsumerKey { get { return consumerKey; } }
        public string Token { get { return token; } }
        public string ConsumerSecret { get { return consumerSecret; } }
        public string TokenSecret { get { return tokenSecret; } }
        public bool HasToken()
        {
            return !string.IsNullOrEmpty(Token);
        }

        public string SignHMACSHA1(string value)
        {
            string utfKey = string.Format("{0}&{1}", ConsumerSecret.Encode(), HasToken () ? TokenSecret.Encode() : string.Empty);
            byte[] utfKeyBytes = Encoding.Default.GetBytes(utfKey);
            byte[] signKey = Encoding.Convert(Encoding.Default, Encoding.ASCII, utfKeyBytes);

            byte[] utfTextBytes = Encoding.Default.GetBytes(value);
            byte[] text = Encoding.Convert(Encoding.Default, Encoding.ASCII, utfTextBytes);


            using (HMACSHA1 crypto = new HMACSHA1(signKey))
            {
                return Convert.ToBase64String(crypto.ComputeHash(text));
            }
        }
    }
}
